<template>
  <!-- 漏斗图组件 -->
  <div class="funnelChart" v-loading="loading">
    <div class="funnelChart-title">
      <!-- <span>漏斗图</span> -->
      <span>{{ chartName }}</span>
    </div>
    <div class="funnelChart-date">
      <div class="funnelChart-date-div">
        <!-- 日期 -->
        <p v-if="screenTime && screenTime.length != 0">
          <span class="left">{{ new Date(screenTime[0]).format("yyyy-MM-dd") }} ~ {{ new
            Date(screenTime[1]).format("yyyy-MM-dd") }}</span>
        </p>
        <!-- el-tooltip -->
        <p class="tooltip-p" v-if="screenTime && screenTime.length != 0">
          <el-tooltip content="筛选时段" placement="bottom" effect="light">
            <img class="right" :src="dateIcon" alt="">
          </el-tooltip>
        </p>
      </div>
      <!-- select -->
      <!-- <el-select v-if="options.length != 0" v-model="queryConditionVal" clearable placeholder="请选择" @change="handleChange">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.name"
          :value="item.value">
        </el-option>
      </el-select> -->
    </div>
    <div style="width: 100%;height: 34px;">
    </div>
    <!-- echarts -->
    <div v-if="payloadData.data && payloadData.data.y.length != 0" :id="'funnelCharts' + id" class="funnelChart-echarts"
      style="width: 100%;height: 272px;"></div>
    <!-- empty -->
    <el-empty v-else :image="emptyImg" description="暂无数据" :image-size="80" style="width: 100%;height: 272px;"></el-empty>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import dateIcon from '@/assets/dataCenter/dataB_dateIcon.png';
import * as echarts from 'echarts';
import emptyImg from '@/assets/dataCenter/dataB_empty.png';
// API
import {
  merchantReportQueryData,
  merchantReportQueryCondition
} from '@/api/dataCenter/dataBoard.js';
// utils
import { dateStrChangeTimeTamp } from './utils.js'
export default {
  name: 'FunnelChart',
  components: {

  },
  props: {
    id: {
      type: Number,
      default: () => {
        return null;
      }
    },
    chartName: {
      type: String,
      default: () => {
        return '';
      }
    }
  },
  inject: ['actId'],
  data() {
    return {
      dateIcon,
      emptyImg,
      data: {},
      payloadData: {},
      multipleData: [],
      relativelyTimeDeal: null,
      loading: false,
      openDataScreenVisible: false,
      dataOptions: [],
      xAxisData: [],
      isScreenComplete: true,
      queryConditionVal: '',
      queryConditionKey: '',
      options: []
    }
  },
  watch: {
    screenTime: {
      handler(val) {
        this.merchantReportQueryDataApi();
      },
      deep: true
    },
    organizationId: {
      handler(val) {
      },
      deep: true
    },
    openDataScreen: {
      handler(val) {
        if (val === this.id) {
          this.openDataScreenVisible = true
        }
      },
      deep: true
    }
  },
  mounted() {
    this.merchantReportQueryDataApi();
  },
  methods: {
    handleChange(val) {
      this.merchantReportQueryDataApi();
    },
    // 获取条件切换接口
    async merchantReportQueryConditionApi() {
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let res = await merchantReportQueryCondition({
        startTime,
        endTime,
        chartType: 4,
        toIndex: 10,
        beanName: this.id,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId: this.actId ?? undefined
      })
      if (res.code === 200) {
        if (res.payload.length != 0) {
          this.options = res.payload[0].options || [];
          this.queryConditionVal = this.options[0].value || '';
          this.queryConditionKey = res.payload[0].key || '';
        }
        this.merchantReportQueryDataApi();
      }
    },
    // 获取报表数据
    async merchantReportQueryDataApi() {
      this.loading = true;
      // screenTime为菜单筛选时间
      let screenTime = store.state.user.screenTime;
      let startTime = '';
      let endTime = '';
      if (screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      }
      let paramStr = {
        startTime,
        endTime,
        chartType: 4,
        toIndex: 10,
        insId: store.state.insId.insId,
        mallId: store.state.user.mallId || '',
        actId: this.actId ?? undefined
      }
      paramStr[this.queryConditionKey] = this.queryConditionVal;
      paramStr = JSON.stringify(paramStr);
      let res = await merchantReportQueryData({
        beanName: this.id,
        param: paramStr,
      })
      if (res.code === 200) {
        this.payloadData = res.payload;
        if (Object.keys(this.payloadData).length != 0) {
          this.capsulationDealData()
        }
      }
      this.loading = false;
    },
    // 数据处理
    capsulationDealData() {
      // 按照图表处理数据
      let legendData = [];
      let seriesData = [];
      if (!this.payloadData.data) {
        return false;
      }
      let valueData = this.payloadData.data.y;
      if (valueData && valueData[0].length === 0) {
        return false;
      }

      valueData[0].forEach(item => {
        legendData.push(item.name)
        let obj = {
          value: null,
          name: '',
        }
        obj.value = Number(item.val);
        obj.name = item.name;
        seriesData.push(obj);
      })
      console.log('funnel', legendData, seriesData)
      this.$nextTick(() => {
        if (valueData.length != 0) {
          this.drawCharts(legendData, seriesData);
        }
      })
    },
    drawCharts(legendData, seriesData) {
      let myChart = echarts.init(document.getElementById('funnelCharts' + this.id));
      //清除残留数据
      myChart.clear()

      //计算总数
      const all = seriesData.reduce((pre, i) => Number((i.value??0)) + pre, 0)
      const data = seriesData.map(item => ({ ...item, value: Math.floor((item.value??0) / all * 100) }))

      let option = {
        tooltip: {
          trigger: 'item',
          formatter: (val) => {
            return `${val.seriesName}<br/>${val.name
              } ${Math.ceil(val.value * all / 100)}`
          }
        },
        legend: {
          data: legendData
        },
        series: [
          {
            name: this.chartName,
            type: 'funnel',
            left: '25%',
            top: 60,
            bottom: 10,
            width: '50%',
            min: 0,
            max: 100,
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
              show: true,
              color: "#333"
            },
            labelLine: {
              length: 120,
              lineStyle: {
                width: 1,
                type: 'solid'
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 1
            },
            emphasis: {
              label: {
                show: true,

              }
            },
            data: data
          }
        ]
      };
      myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (myChart) myChart.resize();
      })
    }
  },
  computed: {
    screenTime() {
      return store.state.user.screenTime;
    },
    organizationId() {
      return store.state.insId.insId;
    },
    openDataScreen() {
      return store.state.user.openDataScreen;
    }
  }
}
</script>

<style lang="scss" scoped>
.funnelChart {
  width: 100%;
  height: 100%;

  &-title {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    span {
      color: #252934;
      height: 24px;
      // width: 112px;
      font-family: PingFangSC-Medium;
      font-size: 16px;
      line-height: 24px;
      cursor: pointer;
    }
  }

  &-date {
    width: 100%;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    // margin-bottom: 34px;
    &-div {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .left {
      font-size: 12px;
      color: #6b798e;
    }

    .right {
      margin-left: 18px;
    }

    .tooltip-p {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  &-tabs {
    width: 100%;
    height: 34px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }

  &-echarts {
    width: 100%;
    height: 42px;

  }
}
</style>

<style lang="scss">
.funnelChart {
  .el-radio-button__inner {
    padding: 6px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }
}
</style>